import {View} from "@tarojs/components";
import DynamicForm, {FormConfig} from "@/components/DynamicForm";
import {useEffect, useRef, useState} from "react";
import LocalData from "@/common/local_data";

import LocalUtils from "@/utils/local_utils";

import AvatarChooser from "@/components/AvatarChooser";
import {updateUserApi, uploadFileApi} from "@/common/apis/home_datasource";
import Utils from "@/utils/common";
import EventUtils from "@/utils/event_utils";
import {Button} from "@antmjs/vantui";
import RouthPath from "@/common/RouthPath";

definePageConfig({
  navigationBarTitleText: '个人信息'
})

export default function AccountSafe() {

  const userInfo = useRef(LocalUtils.getUserinfo());
  const avatar = useRef();
  const childRef = useRef(null); // 仍然使用 useRef

  // 表单配置
  const accountSafeFormConfigs: FormConfig[] = [
    {
      type: 'input',
      inputType: LocalData.phoneInputType,
      maxlength: 11,
      name: 'mobile', // Logical name for recipient name
      label: '手机号码',       // Label text (without *)
      placeholder: '',
      layout: 'horizontal',
      disabled: true,
      rules: []
    },
    {
      type: 'input',
      name: 'realName', // Logical name for recipient name
      label: '真实姓名',       // Label text (without *)
      placeholder: '',
      layout: 'horizontal',
      disabled: true,
      rules: []
    },
    {
      type: 'input',
      name: 'idNo', // Logical name for recipient name
      label: '身份证号',       // Label text (without *)
      placeholder: '',
      layout: 'horizontal',
      disabled: true,
      rules: []
    },
    {
      type: 'input',
      name: 'username', // Logical name for recipient name
      label: '昵称',       // Label text (without *)
      placeholder: '请输入昵称',
      layout: 'horizontal',
      required: true,
    },
    {
      type: 'textarea',
      name: 'company', // Logical name for recipient name
      label: '学校/组织',       // Label text (without *)
      placeholder: '选择学校或输入组织',
      disabled: true,
      minHeight: '10px',
      renderRight: () => {
        return <Button type='primary' size='small' style={{width:"130px"}} onClick={() => {
          Utils.navigateAndListenToEvent(RouthPath.universityList, EventUtils.OK, (data) => {
            if (data) {
              childRef.current?.setFieldValue("company", data)
            }
          })
        }}
        >学校/组织</Button>;
      },
      required: true,
      layout: 'horizontal',
      rules: []
    },
    {
      type: 'render',
      name: 'avatar', // Logical name for recipient name
      label: '',       // Label text (without *)
      renderReactNode: () => {
        return <AvatarChooser defaultAvatarUrl={userInfo.current.avatar} avatar={avatar} title='头像' avatarMarginLeft='75px' />
      },
    },
  ];
  const [initValues, setInitValues] = useState({})
  useEffect(() => {
    setTimeout(() => {
      setInitValues({
        ...userInfo.current,
      })
    }, 50)
  }, []);


  // 提交回调
  const handleSubmit = async (values) => {
    let avatarUrl = userInfo.current.avatar;
    if (avatar.current) {
      const fileModel = await uploadFileApi(avatar.current)
      if (fileModel && fileModel.url) {
        avatarUrl = fileModel.url
      }
    }
    const r = await updateUserApi({
      username: values.username,
      avatar: avatarUrl,
      mobile: values.mobile,
      company: values.company,
    })
    if (r) {
      EventUtils.trigger(EventUtils.UserInfo,true)
      Utils.navigateBack()
    }
    // 处理表单提交逻辑
  };

  // 错误回调
  const handleError = (errors) => {
    console.error('Form errors:', errors);
  };

  return (
    <View>
      {
        initValues.mobile ? <DynamicForm
          ref={childRef}
          initialValues={initValues}
          formConfigs={accountSafeFormConfigs}
          onSubmit={handleSubmit}
          onError={handleError}
          submitText='保存修改'
        /> :
          null
      }
    </View>
  )
}


